/*
Copyright 2013 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package mem

import ()

// RW is a read-write handle to some bytes in memory.  It may be
// invalidated by a caller to prevent a callee from illegally using
// the memory after the documented validity period.
type RW struct {
	b *[]byte
}

// WB returns a writable handle, writing to b.
func WB(b []byte) RW {
	return RW{b: &b}
}

// Len returns the length of m.
func (m RW) Len() int {
	return len(*m.b)
}

// Cap returns the capacity of the slice backing m.
func (m RW) Cap() int {
	return cap(*m.b)
}

// At returns the byte at index i.
func (m RW) At(i int) byte {
	return (*m.b)[i]
}

// Set sets m[i] to b.
func (m RW) Set(i int, b byte) {
	(*m.b)[i] = b
}

// CopyFrom copies bytes
func (m RW) CopyFrom(src RO) int {
	if src.b != nil {
		return copy(*m.b, *src.b)
	}
	return copy(*m.b, src.s)
}

// Temp returns a version of m that is only valid until the returned
// revoke function is called.
func (m RW) Temp() (RW, Revoke) {
	s := *m.b
	return RW{b: &s}, func() { s = nil }
}

// RO returns a read-only view of m.
func (m RW) RO() RO {
	return RO{b: m.b}
}

// Slice returns a slice of m between the provided from and to indices.
func (m RW) Slice(from, to int) RW {
	s := (*m.b)[from:to]
	return RW{b: &s}
}

// SliceFrom slices m from the provided index until the end.
func (m RW) SliceFrom(from int) RW {
	s := (*m.b)[from:]
	return RW{b: &s}
}

// SliceTo slices m from the provided index until the end.
func (m RW) SliceTo(to int) RW {
	return m.Slice(0, to)
}
